<script setup name="aaa">
import { ref, getCurrentInstance } from 'vue'
import { GetListAPI } from '@/api/system/shopAdministration/modeling'
import { TreeListAPI } from '@/api/common'

// import { GetListAPI } from '@/api/system/modeling'
const { proxy } = getCurrentInstance()
// 封装 方法 字典查询
const {
  scheduling_class_info, // 班组
  sys_ofcode_variable, // 时段
} = proxy.useDict('scheduling_class_info', 'sys_ofcode_variable')

const props = defineProps({
  data: {
    type: Object,
    default: () => {},
  },
  disabled: {
    type: Boolean,
    default: false,
  },
})
const ind = ref(null)

// 休息时间的班组下拉
const banzuOpt = ref([])

// 工厂线别数据
const options = ref([])

const Submit = () => {
  const obj = {
    teamCode: tableForm.teamCode,
    restCode: tableForm.restCode,
    lineCodeDto: tableForm.lineCodeDto,
  }

  return obj
}
const tabs = ref('1')
// 新增表单 表格
const tableForm = reactive({
  teamCode: [
    {
      teamInfo: '', //班组
      teamPeriod: '', //时段
      teamStartTime: '', //开始时间
      teamEndTime: '', //结束时间
      teamTranssky: 1, //跨天标识
    },
  ],
  restCode: [
    {
      teamId: '', //班组id
      startTime: '', //开始时间
      endTime: '', //结束时间
      restStartTime: '', //开始时间
      restEndTime: '', //结束时间
      restTranssky: 1, // 跨天标识 1跨 2不跨
    },
  ],
  lineCodeDto: [{ lineCode: '', shopId: '' }],
})

// 勾选新增原料表单 表格
const selectTableOne = ref([])
// 勾选新增原料表单 表格
const selectTableTwo = ref([])
// 勾选新增原料表单 表格
const selectTableThree = ref([])

// 勾选时
const FormTeblChangeOne = (row) => {
  if (tabs.value == 1) selectTableOne.value = row
  if (tabs.value == 2) selectTableTwo.value = row
  if (tabs.value == 3) selectTableThree.value = row
}
// 码段添加
const Add = () => {
  if (tabs.value == 1) {
    tableForm.teamCode.push({
      teamInfo: '', //班组
      teamInfoName: '', //班组名称
      teamPeriod: '', //时段
      teamStartTime: '', //开始时间
      teamEndTime: '', //结束时间
      teamTranssky: 1, //跨天标识
    })
  } else if (tabs.value == 2) {
    tableForm.restCode.push({
      teamId: '', //班组id
      startTime: '', //开始时间
      endTime: '', //结束时间
      restStartTime: '', //开始时间
      restEndTime: '', //结束时间
      restTranssky: 1, // 跨天标识 1跨 2不跨
    })
  } else {
    tableForm.lineCodeDto.push({
      shopId: '',
      lineCode: '',
    })
  }
}

// 删除表格表单
const Remove = (scope) => {
  if (tabs.value == 1) map(tableForm.teamCode, selectTableOne.value)
  if (tabs.value == 2) map(tableForm.restCode, selectTableTwo.value)
  if (tabs.value == 3) map(tableForm.lineCodeDto, selectTableThree.value)
}

// 新增删除 数据
const map = (arr, selectArr) => {
  if (selectArr.length > 0) {
    selectArr.forEach((item) => {
      const Find = arr.findIndex((itemy) => item.infoId == itemy.infoId)
      arr.splice(Find, 1)
    })
  } else {
    arr.splice(arr.length - 1, 1)
  }
}

// 表格hover
const mouseCell = (row) => {
  ind.value = row.$index
}

// 班别信息 班别选择时候 判断不能再次选择
const teamInfoChange1 = (val) => {
  // 查找休息时间 选中班别与班别信息相同的值 做清除
  // const ind = tableForm.restCode.findIndex(item => item.teamInfo == val)
  // 清除相同班别
  // if (ind !== -1) tableForm.restCode.splice(ind, 1)
  tableForm.restCode = [{ shopId: '', lineCode: '' }]
  let num = 0
  tableForm.teamCode.forEach((item) => {
    if (val == item.teamInfo) num++
  })
  if (num > 1) {
    tableForm.teamCode[ind.value].teamInfo = ''
    proxy.warningMsg('不可选择相同的班别')
  }
}

// 休息时间 班别选择时候
const teamInfoChange = (val) => {
  const Obj = tableForm.teamCode.find((item) => val == item.teamInfo)
  if (!Obj) return console.error('错误')
  tableForm.restCode[ind.value] = {
    teamInfo: val,
    teamId: val,
    startTime: Obj.teamStartTime,
    endTime: Obj.teamEndTime,
    restStartTime: '',
    restEndTime: '',
    restTranssky: 1,
  }
}

// 监听数据
watch(
  () => tabs.value,
  (val, lodVal) => {
    if (val == 2 && tableForm.teamCode.length > 0) {
      const arr = []
      tableForm.teamCode.forEach((item) => {
        const Obj = scheduling_class_info.value.find(
          (selsctItem) => selsctItem.value == item.teamInfo
        )
        if (!Obj) return console.error('班别信息查找错误')
        arr.push({
          label: Obj.label,
          value: Obj.value,
        })
      })

      banzuOpt.value = arr
    }
  }
)

// 校验班别信息 结束时间大于开始时间 且跨天开启
const teamEndTimeChange = (obj) => {
  const teamStartTime = Date.parse(`2023-01-01 ${obj.teamStartTime}`)
  const teamEndTime = Date.parse(`2023-01-01 ${obj.teamEndTime}`)
  if (!obj.teamStartTime) {
    obj.teamEndTime = ''
    proxy.warningMsg('请先选择开始时间!')
    return
  }

  if (obj.teamTranssky == 2 && teamStartTime > teamEndTime) {
    obj.teamEndTime = ''
    return proxy.warningMsg('结束时间小于开始时间')
  }
}

/**
 * 校验开始时间
 */
const endTimeChange = (v) => {
  console.log(v, 'teamTranssky------')
  // 结束时间
  let teamEnd = v.teamEndTime?.split(':')[0]
  // 结束时间
  let startTime = v.teamStartTime?.split(':')[0]
  v.teamTranssky = parseFloat(startTime) > parseFloat(teamEnd) ? 0 : 1
}

// 校验 开始时间 在结束时间和班别开始时间之间
const restStartTimeChange = (obj) => {
  if (!obj.startTime || !obj.endTime) {
    obj.restStartTime = ''
    return proxy.warningMsg('请先选择班别开始时间和班别结束时间!')
  }
  const startTime = Date.parse(`2023-01-01 ${obj.startTime}`)
  const endTime = Date.parse(`2023-01-01 ${obj.endTime}`)
  const restStartTime = Date.parse(`2023-01-01 ${obj.restStartTime}`)
  if (restStartTime > startTime && restStartTime < endTime) {
  } else {
    obj.restStartTime = ''
    return proxy.warningMsg('“开始时间”须在班别开始与结束时间之间!')
  }
}

// 编码
const objChange = (val) => {
  // console.log(val, 'val')
  // const result = options.value.find((item) => {
  //   // if(item)
  //   if(item.id==val){
  //   }
  //   console.log(item)
  // })
  // if (result) {
  //   proxy.warningMsg('已选择该线别，请勿重复选择')
  //   tableForm.lineCodeDto.splice(ind.value, 1)
  //   return
  // }
  // tableForm.lineCodeDto[ind.value].lineCode = val.info.code
}
// 获取工厂数据
const get = async () => {
  const { data: res } = await TreeListAPI()
  console.log(res)

  options.value = res
}
get()

// 回显

watch(
  () => props.data,
  () => {
    if (props.data) {
      let data =
        typeof props.data != 'object' ? JSON.parse(props.data) : props.data
      if (typeof props.data == 'string') {
        data.lineCodeDto?.map((t) => (t.shopId = t.shopId.split(',')))
      }
      tableForm.lineCodeDto = data.lineCodeDto || []
      tableForm.restCode = data.restCode || []
      tableForm.teamCode = data.teamCode || []

      for (let KEY in data) {
        if (data[KEY]?.length > 0) tableForm[KEY] = data[KEY]
      }
    }
  },
  {
    deep: true,
    immediate: true,
  }
)

defineExpose({ Submit })
</script>
<template>
  <div class="app-container">
    <el-tabs type="border-card" v-model="tabs">
      <!-- 班别信息 -->
      <el-tab-pane label="班别信息" name="1">
        <div class="caozuo" v-if="!props.disabled">
          <el-tooltip
            class="box-item"
            effect="dark"
            content="添加"
            placement="top-start"
          >
            <el-icon @click="Add"><Plus /></el-icon>
          </el-tooltip>
          <div style="margin: 0 10px"></div>
          <el-tooltip
            class="box-item"
            effect="dark"
            content="勾选删除"
            placement="top-start"
          >
            <el-icon @click="Remove()"><Minus /></el-icon>
          </el-tooltip>
        </div>
        <el-table
          stripe
          border
          :data="tableForm.teamCode"
          @selection-change="FormTeblChangeOne"
        >
          <el-table-column
            type="selection"
            width="55"
            align="center"
            fixed="left"
          />
          <el-table-column
            label="序号"
            type="index"
            width="80"
          ></el-table-column>
          <el-table-column label="班别" width="auto">
            <template #default="scope">
              <div @mouseover="mouseCell(scope)">
                <el-select
                  :disabled="props.disabled"
                  v-model="scope.row.teamInfo"
                  clearable
                  placeholder="请选择"
                  @change="teamInfoChange1"
                >
                  <el-option
                    v-for="(item, index) in scheduling_class_info"
                    :key="index"
                    :label="item.label"
                    :value="item.value"
                  />
                </el-select>
              </div>
            </template>
          </el-table-column>
          <el-table-column label="时段" width="auto">
            <template #default="scope">
              <el-select
                :disabled="props.disabled"
                v-model="scope.row.teamPeriod"
                clearable
                placeholder="请选择"
              >
                <el-option
                  v-for="(item, index) in sys_ofcode_variable"
                  :key="index"
                  :label="item.label"
                  :value="item.value"
                />
              </el-select>
            </template>
          </el-table-column>
          <el-table-column label="开始时间" width="220">
            <template #default="scope">
              <el-time-picker
                :disabled="props.disabled"
                v-model="scope.row.teamStartTime"
                value-format="HH:mm:ss"
                placeholder="开始时间"
              />
            </template>
          </el-table-column>
          <el-table-column label="结束时间" width="220">
            <template #default="scope">
              <el-time-picker
                value-format="HH:mm:ss"
                :disabled="props.disabled"
                v-model="scope.row.teamEndTime"
                placeholder="结束时间"
                @change="endTimeChange(scope.row)"
              />
            </template>
          </el-table-column>
          <el-table-column label="跨天标识" width="auto">
            <template #default="scope">
              <p-switch disabled v-model="scope.row.teamTranssky" />
            </template>
          </el-table-column>
        </el-table>
      </el-tab-pane>
      <!-- 休息时间 -->
      <el-tab-pane label="休息时间" name="2">
        <div class="caozuo" v-if="!props.disabled">
          <el-tooltip
            class="box-item"
            effect="dark"
            content="添加"
            placement="top-start"
          >
            <el-icon @click="Add"><Plus /></el-icon>
          </el-tooltip>
          <div style="margin: 0 10px"></div>
          <el-tooltip
            class="box-item"
            effect="dark"
            content="勾选删除"
            placement="top-start"
          >
            <el-icon @click="Remove()"><Minus /></el-icon>
          </el-tooltip>
        </div>
        <el-table
          stripe
          border
          :data="tableForm.restCode"
          @selection-change="FormTeblChangeOne"
        >
          <el-table-column
            type="selection"
            width="55"
            align="center"
            fixed="left"
          />
          <el-table-column
            label="序号"
            type="index"
            width="80"
          ></el-table-column>
          <el-table-column label="班别" width="220">
            <template #default="scope">
              <div @mouseover="mouseCell(scope)">
                <el-select
                  :disabled="props.disabled"
                  v-model="scope.row.teamInfo"
                  clearable
                  placeholder="请选择"
                  @change="teamInfoChange"
                >
                  <el-option
                    v-for="(item, index) in banzuOpt"
                    :key="index"
                    :label="item.label"
                    :value="item.value"
                  />
                </el-select>
              </div>
            </template>
          </el-table-column>

          <el-table-column label="班别开始时间" width="220">
            <template #default="scope">
              <el-time-picker
                :disabled="props.disabled || banzuOpt.length > 0"
                v-model="scope.row.startTime"
                placeholder="开始时间"
                value-format="HH:mm:ss"
              />
            </template>
          </el-table-column>
          <el-table-column label="班别结束时间" width="220">
            <template #default="scope">
              <el-time-picker
                @change="teamEndTimeChange(scope.row)"
                :disabled="props.disabled || banzuOpt.length > 0"
                v-model="scope.row.endTime"
                value-format="HH:mm:ss"
                placeholder="结束时间"
              />
            </template>
          </el-table-column>

          <el-table-column label="开始时间" width="220">
            <template #default="scope">
              <el-time-picker
                :disabled="props.disabled"
                v-model="scope.row.restStartTime"
                placeholder="开始时间"
                value-format="HH:mm:ss"
                @change="restStartTimeChange(scope.row)"
              />
            </template>
          </el-table-column>
          <el-table-column label="结束时间" width="220">
            <template #default="scope">
              <el-time-picker
                :disabled="props.disabled"
                v-model="scope.row.restEndTime"
                placeholder="结束时间"
                value-format="HH:mm:ss"
              />
            </template>
          </el-table-column>
          <el-table-column label="跨天标识" width="auto">
            <template #default="scope">
              <p-switch
                :disabled="props.disabled"
                v-model="scope.row.restTranssky"
                active="0"
                inactive="1"
              />
            </template>
          </el-table-column>
        </el-table>
      </el-tab-pane>
      <!-- 线别设置 -->
      <el-tab-pane label="线别设置" name="3">
        <div class="caozuo" v-if="!props.disabled">
          <el-tooltip
            class="box-item"
            effect="dark"
            content="添加"
            placement="top-start"
          >
            <el-icon @click="Add"><Plus /></el-icon>
          </el-tooltip>
          <div style="margin: 0 10px"></div>
          <el-tooltip
            class="box-item"
            effect="dark"
            content="勾选删除"
            placement="top-start"
          >
            <el-icon @click="Remove()"><Minus /></el-icon>
          </el-tooltip>
        </div>
        <el-table
          stripe
          border
          :data="tableForm.lineCodeDto"
          @selection-change="FormTeblChangeOne"
        >
          <el-table-column
            type="selection"
            width="55"
            align="center"
            fixed="left"
          />
          <el-table-column
            label="序号"
            type="index"
            width="80"
          ></el-table-column>
          <el-table-column label="线别" width="auto">
            <template #default="scope">
              <div @mouseover="mouseCell(scope)" class="Cascader">
                <!-- <el-select
                  v-model="scope.row.shopIds"
                  placeholder="线别"
                  size="large"
                  multiple
                  style="width: 140px"
                  @change="objChange"
                >
                  <el-option
                    v-for="item in options"
                    :key="item.id"
                    :label="item.regionName"
                    :value="item.id"
                  />
                </el-select> -->

                <el-cascader
                  v-model="scope.row.shopId"
                  :options="options"
                  :disabled="props.disabled"
                  :props="{
                    label: 'regionName',
                    value: 'id',
                    children: 'children',
                  }"
                  @change="handleChange"
                />
                <!-- <p-cascader
                  @change="objChange"
                  :disabled="props.disabled"
                  v-model="scope.row.shopId"
                  :prop="{
                    value: 'id',
                    children: 'children',
                    label: 'name',
                  }"
                  :options="options"
                /> -->
              </div>
            </template>
          </el-table-column>
          <!-- <el-table-column label="工厂编码" width="auto">
            <template #default="scope">
              <el-input disabled v-model="scope.row.lineCodeDto" />
            </template>
          </el-table-column> -->
        </el-table>
      </el-tab-pane>
    </el-tabs>
  </div>
</template>

<style scoped lang="scss">
.caozuo {
  float: right;
  display: flex;
  margin-bottom: 10px;
  justify-content: space-evenly;
}
.app-container ::v-deep .el-input__inner {
  width: 120px !important;
}
.app-container ::v-deep .el-input {
  width: 120px !important;
}
.Cascader ::v-deep .el-input__inner {
  width: 400px !important;
}
.Cascader ::v-deep .el-input {
  width: 400px !important;
}
</style>
